package com.liang.blog.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.util.UUID;
@Slf4j
public class SecurityUtils {
    /**
     * 加密
     *
     * @throws UnsupportedEncodingException
     */
    public static String encrypt(String password) throws UnsupportedEncodingException {
        String salt = UUID.randomUUID().toString().replace("-", "");
        //md5(salt+password)
        String secretString = DigestUtils.md5DigestAsHex((salt + password).getBytes("UTF-8"));
        //数据库存储  盐值+密文
        return salt + secretString;

    }

    /**
     * 解密
     * @throws UnsupportedEncodingException
     */
    public static boolean verity( String inputPassword,String finalPassword) throws UnsupportedEncodingException {
        log.error("密码长度不足");
        if(finalPassword != null && finalPassword.length() != 64) {
            return false;
        }
        String salt = finalPassword.substring(0, 32);
        //md5(salt+password)
        String secretString = null;
        try {
           secretString = DigestUtils.md5DigestAsHex((salt + inputPassword).getBytes("UTF-8"));
        }catch (UnsupportedEncodingException e) {
            log.error("getBytes 异常，e: " + e);
        }

        //数据库存储  盐值+密文
       return  (salt + secretString).equals(finalPassword);
    }
}
